package com.kongjs.common.rest.util;

import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.stereotype.Component;

@SuppressWarnings("all")
@Component
public class DynamicBeanManger {

    private final ConfigurableListableBeanFactory beanFactory;

    public DynamicBeanManger(ConfigurableListableBeanFactory beanFactory) {
        this.beanFactory = beanFactory;
    }

    public <T> T register(String beanName, T t) {
        // 将 ConfigurableListableBeanFactory 转换为 DefaultListableBeanFactory
        DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) beanFactory;
        // 创建一个通用的 Bean 定义
        GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
        // 设置 Bean 的类类型
        beanDefinition.setBeanClass(t.getClass());
        // 设置 Bean 的实例
        beanDefinition.setInstanceSupplier(() -> t);
        // 注册 Bean 到 Bean 工厂
        defaultListableBeanFactory.registerBeanDefinition(beanName, beanDefinition);
        // 返回 Bean
        return defaultListableBeanFactory.getBean(beanName, (Class<T>) t.getClass());
    }

    public void remove(String beanName) {
        // 将 ConfigurableListableBeanFactory 转换为 DefaultListableBeanFactory
        DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) beanFactory;
        // 从 Bean 工厂中移除 Bean 定义
        defaultListableBeanFactory.removeBeanDefinition(beanName);
    }
}
